import { DIST_TYPE } from "@/constant";
import { get } from "@/utils/http/httpUtil";

// 定义 state
const state = {
    value: [],
    isInit: true
};

// 定义 getters
const getters = {
    val: (state) => () => state.value
};

// 定义 mutations
const mutations = {
    // 设置 value 状态
    SET_VALUE(state, value) {
        state.value = value;
    },
    // 设置 isInit 状态
    SET_IS_INIT(state, isInit) {
        state.isInit = isInit;
    }
};

// 定义 actions
const actions = {
    async init({ dispatch, state }, http) {
        if (state.isInit) {
            await dispatch('initValue', http);
        }
    },
    async initValue({ commit, dispatch }, http) {
        commit('SET_IS_INIT', false);
        let dictItems = localStorage.getItem(DIST_TYPE);
        if (dictItems) {
            let value = JSON.parse(dictItems);
            commit('SET_VALUE', value);
        } else {
            await dispatch('refresh', http);
        }
    },
    async refresh({ commit }, http) {
        await get( '/online/sysDictType/listOnline').then((v) => {
            for (let o of v) {
                o.dictLabel = o.name;
                o.dictValue = String(o.code);
                o.label = o.name;
                o.value = String(o.code);
            }
            localStorage.setItem(DIST_TYPE, JSON.stringify(v));
            commit('SET_VALUE', v);
        });
    }
};

// 导出命名空间模块
export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
};
